/*
 * Timer.cpp
 *
 *  Created on: Nov 5, 2014
 *      Author: root
 */
#include "Timer.h"

namespace TimerNameSpace {

void* Timer::Counting(void* sec)
{
	int *seconds=(int*)sec;
   while (*seconds!=0)
   {
	sleep(1);
   *seconds-=1;
   }
   pthread_exit(NULL);
}

	bool Timer::CountDown(signed int *seconds)
	{
		if (*seconds>0)
		{
			pthread_t thread;
			pthread_create(&thread, NULL, Counting, seconds);
			return true;
		}
		else
		{
			std::cout << "'seconds' parameter cannot be negative or zero!"<< std::endl;
			return false;
		}
	}

	void* Timer::KillThreadByTimeOut(void* args)
	{
		pthread_t *myArgs=(pthread_t*)args;

		sleep(myArgs[1]);
		pthread_cancel(myArgs[0]);
	}


	void* Timer::TimeOutFunc(void* func(void *), void* funcParam, int timeOut)
	{
		void *retValue;
		pthread_t functhread,killThread;
		pthread_t argsToKillFunc[2];

		pthread_create(&functhread, NULL, func, funcParam);

		argsToKillFunc[1]=(pthread_t)timeOut;
		argsToKillFunc[0]=functhread;
		pthread_create(&killThread, NULL, KillThreadByTimeOut, (void*)&argsToKillFunc);

		pthread_join(functhread, &retValue);
		pthread_cancel(killThread);
		return retValue;

	}


} /* namespace TimerNameSpace */




